'use client'
import React, { useState, useMemo, useEffect } from "react";
import { Input, ConfigProvider, Tooltip, Button, message, Upload } from 'antd';
import { LinkOutlined, SendOutlined, OpenAIOutlined, ChromeOutlined } from '@ant-design/icons'
import type { UploadFile } from 'antd';
import KeyStore from '@/app/store/key'
import './index.scss'
import SoundRecording from './Soundrecording/page'
import Modalui from './Modalui/page'

const { TextArea } = Input;

interface ChatInputProps {
    setData: (data: { value: string; fileList: any, flag?: boolean }) => void;
    disabled: boolean
}

const ChatInput = React.memo(function ({ setData, disabled }: ChatInputProps) {

    const [agentContent, setagentContent] = useState<HTMLElement>()
    const [value, setValue] = useState<string>('');
    const [fileList, setFileList] = useState<UploadFile[]>([])

    const { user, key, isdoc } = KeyStore()
    const [think, setthink] = useState<boolean>(true)
    const [open, setopen] = useState<boolean>(false)

    useEffect(() => {
        try {
            const agentContent = document.querySelector('.agentContent') as HTMLElement
            setagentContent(agentContent)
        } catch (error) {
        }
    }, [agentContent])

    const [flag, setflag] = useState(false)

    const isflag = useMemo(() => {
        if (disabled) {
            return true
        }
        return value.trim() == ''
    }, [value])

    const obtain = async () => {
        let flag = false
        setData({ value, fileList, flag })
        setValue(value)
        setValue('')
        setFileList([])
        if (agentContent) { agentContent.style.maxHeight = '700px'; }
    }


    const props: any = {
        name: 'file',
        action: `/api/files/upload`,
        headers: {
            authorization: `Bearer ${key}`,
        },
        method: 'POST',
        listType: "picture",
        fileList: fileList,

        data: () => ({
            user: user,
        }),
        onSuccess(response: any, file: any) {
            try {
                if (agentContent) {
                    agentContent.style.maxHeight = '500px';
                }
                message.success(`${file.name} 上传成功`);
                setFileList(prev => [...prev, response]);
                setflag(!flag)
            } catch {
                message.error("上传失败");
            }
        },
        beforeUpload(file: any) {
            const isImage = file.type.startsWith('image/');
            if (isImage) {
                message.error('不允许上传图片!');
                return false; // 阻止上传
            }
            return true;
        },
        onRemove(file: any) {
            const newFileList = fileList.filter((f: any) => f.id !== file.id);
            setFileList(newFileList);
            if (newFileList.length === 0 && agentContent) {
                agentContent.style.maxHeight = '600px';
            }
            return true;
        },
    };

    const handleKeyPress = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            obtain()
        }
    };
    return (
        <div className="chatinput">
            <div className='chatinputbox'>
                <ConfigProvider
                    theme={{ components: { Input: { activeBorderColor: '#cecece', activeBg: '#fff', hoverBorderColor: '#cecece' } } }} >
                    <TextArea value={value}
                        onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setValue(e.target.value)}
                        placeholder='给 DeepSeek 发送消息'
                        autoSize={{ minRows: 3, maxRows: 3 }}
                        onKeyDown={handleKeyPress}
                    />
                </ConfigProvider>
                <div className="chatbutton">
                    <div className="chatbuttonleft">
                        {
                            isdoc ? <Button icon={<ChromeOutlined />} onClick={() => { setopen(true) }}>润色/纠错</Button> :
                                <Button icon={<OpenAIOutlined />} className={think ? 'active' : ''}
                                    onClick={() => { setthink(!think) }}>深度思考</Button>
                        }
                    </div>
                    <div className="chatbuttonright">
                        <Tooltip placement="top" title='支持上传文件(最多5个，每个15MB以内)接受 TXT, MD, MDX, MARKDOWN, PDE HTML, XLSX,XLS, DOCX, CSV EML, MSG, PPTX, PPT, XML EPUB等' >
                            <Upload {...props}><LinkOutlined /></Upload>
                        </Tooltip>
                        <Tooltip placement="top" title='语音输入'>
                            <><SoundRecording onSend={(text: string) => {
                                setValue(text)
                            }} /></>
                        </Tooltip>

                        <Tooltip placement="top" title='向AI进行提问' >
                            <Button type="primary" icon={<SendOutlined />} onClick={() => {
                                obtain()
                            }} disabled={isflag} />
                        </Tooltip>

                    </div>
                </div>
                {
                    fileList.length != 0 &&
                    <div className="chatupload">
                    </div>
                }
            </div>
            <p>内容由 AI 大模型生成，请仔细甄别</p>
            <Modalui setDate={(value) => {
                setopen(value)
            }} open={open} />
        </div>
    )
})

export default ChatInput